//
//  LNNewsViewController.m
//  NetEaseNewsDemo
//
//  Created by Lining on 15/5/11.
//  Copyright (c) 2015年 Lining. All rights reserved.
//

#import "LNNewsViewController.h"
#import "LNChannel.h"
#import "LNChannelLabel.h"
#import "LNChannelCell.h"
#import "YYSettingViewController.h"
#import "YYPopoverPresentationController.h"
#import "ChannelEditCollectionViewController.h"

@interface LNNewsViewController () <UICollectionViewDataSource, UICollectionViewDelegate, LNChannelLabelDelegate,UIViewControllerTransitioningDelegate>
/// 频道数组
@property (nonatomic, strong) NSArray *channelsList;
/// 频道视图
@property (weak, nonatomic) IBOutlet UIScrollView *channelView;
/// 布局参数
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
/// 新闻视图
@property (weak, nonatomic) IBOutlet UICollectionView *newsView;
///  当前显示标签索引
@property (nonatomic, assign) NSInteger currentIndex;
@end

@implementation LNNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 取消自动调整边距
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupNavgationStyle];
    [self setupChannelsLabel];
}

#pragma mark - 设置导航栏样式 频道标签
/**
 *  设置导航栏样式
 */
- (void)setupNavgationStyle {
    
    // 设置标题视图
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navbar_netease"] highlightedImage:nil];
    self.navigationItem.titleView = imgView;
}

/**
 *  设置频道标签
 */
- (void)setupChannelsLabel {
    
    CGFloat margin = 8;
    CGFloat x = margin;
    CGFloat y = 0;
    CGFloat h = self.channelView.bounds.size.height;
    CGFloat w = 20;
    NSInteger index = 0;
    for (LNChannel *channel in self.channelsList) {
        LNChannelLabel *label = [LNChannelLabel labelWithTitle:channel.tname];
        label.frame = CGRectMake(x, y, label.bounds.size.width + w, h);
        label.delegate = self;
        [self.channelView addSubview:label];
        x += label.bounds.size.width;
        label.tag = index++;
    }
    self.channelView.contentSize = CGSizeMake(x + margin, h);
    self.channelView.showsHorizontalScrollIndicator = NO;
    // 初始选中第0个标签
    self.currentIndex = 0;
    LNChannelLabel *label = self.channelView.subviews[0];
    label.scale = 1;
}

#pragma mark - uicollectionView的数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.channelsList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LNChannelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewsCollectionCell" forIndexPath:indexPath];
    
    // 添加子视图控制器 如果不添加子视图控制器 会破坏响应者链条，打断消息传递，有可能产生非常怪异的 bug
    if (![self.childViewControllers containsObject:cell.newsVC]) {
        [self addChildViewController:(UIViewController *)cell.newsVC];
    }
    
    // 设置 cell
    cell.urlStr = [self.channelsList[indexPath.item] urlStr];
    return cell;
}

#pragma mark - LNChannelLabel的代理方法
- (void)channelLabelDidSelected:(LNChannelLabel *)label {
    self.currentIndex = label.tag;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:label.tag inSection:0];
    [self.newsView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

#pragma mark - scrollView的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    // 从哪个标签切换到哪一个标签
    LNChannelLabel *currentLabel = self.channelView.subviews[self.currentIndex];
    LNChannelLabel *nextLabel = nil;
    
    // collectionView indexPathsForVisibleItems 获取当前所有显示的 cell 的 indexPath
    NSArray *indexPaths = [self.newsView indexPathsForVisibleItems];
    // 遍历 indexPaths
    for (NSIndexPath *path in indexPaths) {
        if (path.item != self.currentIndex) {
            nextLabel = self.channelView.subviews[path.item];
            break;
        }
    }
    
    // NSLog(@"%@ － %@", currentLabel.text, nextLabel.text);
    // 如果没有下一个标签，直接返回
    if (nextLabel == nil) {
        return;
    }
    
    // 知道变化了多少
    float nextScale = ABS((float)scrollView.contentOffset.x / scrollView.bounds.size.width - self.currentIndex);
    float currentScale = 1 - nextScale;
    // NSLog(@"%f %f", currentScale, nextScale);
    
    currentLabel.scale = currentScale;
    nextLabel.scale = nextScale;
    // 更新当前标签索引
    self.currentIndex = scrollView.contentOffset.x / scrollView.bounds.size.width;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 更新当前标签索引
    self.currentIndex = scrollView.contentOffset.x / scrollView.bounds.size.width;
    
    // 计算当前选中标签的中心点
    LNChannelLabel *label = self.channelView.subviews[self.currentIndex];
    CGFloat offset = label.center.x - self.channelView.bounds.size.width * 0.5;
    CGFloat maxOffset = self.channelView.contentSize.width - self.channelView.bounds.size.width;
    
    if (offset < 0) {
        offset = 0;
    } else if (offset > maxOffset) {
        offset = maxOffset;
    }
    
    [self.channelView setContentOffset:CGPointMake(offset, 0) animated:YES];
}

#pragma mark - 自定义转场
/// 实现首页导航栏方块按钮跳转
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [super prepareForSegue:segue sender:sender];
    if ([segue.identifier isEqualToString:@"square"])
    {
        YYSettingViewController *squareVC = segue.destinationViewController;
        squareVC.transitioningDelegate = self;
        squareVC.modalPresentationStyle = UIModalPresentationCustom;
    } else if ([segue.identifier isEqualToString:@"ChannelEdit"]) {
        ChannelEditCollectionViewController *channelEditVC = segue.destinationViewController;
        channelEditVC.transitioningDelegate = self;
        channelEditVC.modalPresentationStyle = UIModalPresentationCustom;
    }
}

-(UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    
    return [[YYPopoverPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    
}


#pragma mark - 布局子视图 设置布局属性
/**
 *  布局子视图
 */
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.layout.itemSize = self.newsView.bounds.size;
    self.layout.minimumInteritemSpacing = 0;
    self.layout.minimumLineSpacing = 0;
    self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.newsView.pagingEnabled = YES;
    self.newsView.showsHorizontalScrollIndicator = NO;
    
}

#pragma mark - 懒加载
- (NSArray *)channelsList {
    if (_channelsList == nil) {
        _channelsList = [LNChannel channelsList];
    }
    return _channelsList;
}
@end
